import {Graph, Cell, DragSource, gestureUtils} from "@maxgraph/core";
// import type DropHandler from "@maxgraph/core/dist/view/other/DragSource";
import {DropHandler} from "@maxgraph/core/dist/view/other/DragSource";

let props = {
    widget: '',
    w: 80,
    h: 80,
}
let size = {
    width: 80,
    height: 80
}
const dropHandler: DropHandler = function (graph: Graph, evt: MouseEvent, target: Cell, x?: number, y?: number): void {
    // console.log(props)
    let dx: number = x! - props.w / 2
    let dy: number = y! - props.h / 2
    const parent: Cell = graph.getDefaultParent()
    const scale = graph.getView().scale
    const tr = graph.getView().translate

    const cells: Cell[] = []
    graph.batchUpdate(() => {
        const lvgl: Cell = graph.insertVertex(parent,
            null,
            '',
            dx - tr.x,
            dy - tr.y,
            props.w * scale,
            props.h * scale,
        )
        cells.push(lvgl)
    })
    if (cells && cells.length > 0) {
        graph.scrollCellToVisible(cells[0]);
        graph.setSelectionCells(cells);
    }
};
export default function (graph?: Graph){
    if (!graph) {
        return
    }
    // 创建一个禁止放置的图标
    const forbit = document.createElement('img') as HTMLImageElement
    forbit.style.width = '35px'
    forbit.style.height = '35px'
    forbit.src = './forbid.png'
    forbit.style.transform = 'translate(-50%,-70%)'


    const divImgs = document.querySelectorAll('.shape-item')
    divImgs.forEach((item) => {
        const img: HTMLImageElement = item.children[0].children[0] as HTMLImageElement
        // 设置预览图形
        let width = 80
        let height = 80
        size = {
            width, height
        }

        // 为所有的绑定一个事件可以使点击传递过来值
        // item.addEventListener('mousedown', (e) => {
        //     // 这里不能用上面的已经取出来的值 上边的值不是实时的
        //     let target = e.currentTarget as HTMLDivElement
        //     let widget = target.children[1].innerHTML
        //     let w = item.dataset['defaultW']
        //     let h = item.dataset['defaultH']
        //     w = w ? parseInt(w) : 80
        //     h = h ? parseInt(h) : 80
        //     props = {
        //         widget, w, h
        //     }
        // })

        // 设置预览图形
        const dragEle = document.createElement('img') as HTMLImageElement
        dragEle.style.width = size.width + 'px'
        dragEle.style.height = size.height + 'px'
        dragEle.style.objectFit = 'contain'
        dragEle.style.border = 'dashed black 1px';
        dragEle.style.transform = 'translate(-50%,-50%)'

        const ds: DragSource = gestureUtils.makeDraggable(img, graph, dropHandler, dragEle, null, null,
            graph.autoScroll, true, true)
        // 设置预览图形的导航
        ds.isGuidesEnabled = function () {
            return true;
        };
        // 当拖动到不可放置的位置时，会出现禁止放置的图表
        ds.createDragElement = () => {
            return forbit.cloneNode(true) as HTMLElement
        };
    })
}
